package com.deyun.measuredistance;

import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;

import com.apkfuns.logutils.LogUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.Timer;
import java.util.TimerTask;

import androidx.appcompat.app.AppCompatActivity;
import me.f1reking.serialportlib.SerialPortHelper;
import me.f1reking.serialportlib.listener.ISerialPortDataListener;

public class MainActivity extends AppCompatActivity {
    public SerialPortHelper serialPortHelper;
    public Timer timer = new Timer();

    public String str_distance = "";
    public String url = "http://10.1.30.16:8080/distance";

    // byte数组转成字符串
    public String byteToArray(byte[] data) {
        String result = "";
        for (int i = 0; i < data.length; i++) {
            result += Integer.toHexString((data[i] & 0xFF) | 0x100).toUpperCase().substring(1, 3);
        }
        return result;
    }

    // 获取距离
    public String getDistance(String str) {
        String str_one = str.substring(2, 4);
        String str_two = str.substring(6, 8);
        int a = Integer.valueOf(str_one, 16) * 256;
        int b = Integer.valueOf(str_two, 16);
        return (a + b) + "毫米";
    }


    public void submitDataToServer() {

        RequestParams params = new RequestParams(url);
        params.setCacheMaxAge(0);
        params.setMultipart(true);
        params.addBodyParameter("distance", str_distance);
        LogUtils.d("upload_url = " + params.getUri());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                LogUtils.d("result = " + result);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                LogUtils.d("onError = " + ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                LogUtils.d("我执行了 str_distance = " + str_distance);
                submitDataToServer();
            }
        };

        timer.schedule(task, 1000, 1000);
        serialPortHelper = new SerialPortHelper();
        // 串口地址
        serialPortHelper.setPort("/dev/ttyS1");
        // 波特率0
        serialPortHelper.setBaudRate(9600);
        // 停止位
        serialPortHelper.setStopBits(1);
        // 打开串口
        serialPortHelper.open();
        // 串口数据监听
        serialPortHelper.setISerialPortDataListener(new ISerialPortDataListener() {
            @Override
            public void onDataReceived(byte[] bytes) {
                String str = byteToArray(bytes);
                // LogUtils.d("收到的数据=" + getDistance(str));
                //LogUtils.d("获取的距离 = " + getDistance(str));
                str_distance = getDistance(str);
                // getTime(str);
                // FF039597 FF015A5A
            }

            @Override
            public void onDataSend(byte[] bytes) {
                LogUtils.d("发送的数据 = " + byteToArray(bytes));
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtils.d("onDestroy");
        timer.cancel();
        timer = null;

        Intent intent = new Intent();
        //第一种方式
        ComponentName cn = new ComponentName("com.deyun.measuredistance", "com.deyun.measuredistance.MainActivity");
        try {
            intent.setComponent(cn);
            //第二种方式
            //intent.setClassName("com.example.fm", "com.example.fm.MainFragmentActivity");
            // intent.putExtra("test", "intent1");
            startActivity(intent);
        } catch (Exception e) {
            //TODO  可以在这里提示用户没有安装应用或找不到指定Activity，或者是做其他的操作
            LogUtils.d("exception = " + e);
        }


    }


}